import { initWebsocket } from '@/utils/socket'
import { sendSock } from '@/utils/socketSend'
import { DH, md5ArrayBuffer } from '@/secret/secret'

const state = {
  // websocket实例对象
  webSocket: null,
  // 发送请求后的回调函数
  globalCallback: null,
  // 请求编号
  req_id: 0,
  // DH密钥
  DHSecretKey: null,
  // 操作成功/失败的req_id存储对象，来判断是否需要重新操作
  reqList: {},
  // 各操作的reqId
  operationReqId: {
    // 身份认证的reqId
    identityReqId: null,
    // 发出消息的reqId
    sendMessageId: null,
    // 撤回消息的reqId
    withdrawReqId: null,
    // 取消通话的reqId
    cancelVideoCallId: null,
    // 拒绝通话的reqId
    refuseVideoCallId: null,
    // 接受通话的reqId
    acceptVideoCallId: null,
    // 通话关闭摄像头成功的reqId
    closeCameraReqId: null,
    // 通话打开摄像头成功的reqId
    openCameraReqId: null,
    // 拉取未读消息的reqId
    pullUnreadMessageReqId: null,
    // 拉取最近联系人列表的reqId
    pullRecentContactsListReqId: null,
    // 拉取历史记录的reqId
    pullHistoryRecordReqId: null,
    // 加入会议的reqId
    joinConferenceReqId: null
  },
  // 处理字节数组得到的结果数组
  resArr: []
}

const mutations = {
  // 设置websocket实例对象
  set_webSocket (state, ws) {
    state.webSocket = ws
  },
  // 设置发送请求后的回调函数
  set_globalCallback (state, fn) {
    state.globalCallback = fn
  },
  // 设置请求编号
  set_req_id (state) {
    if (state.req_id === 100000000) {
      state.req_id = 1
    } else {
      state.req_id++
    }
  },
  // 设置DH密钥
  set_DHSecretKey (state, key) {
    state.DHSecretKey = key
  },
  // 设置reqList,新的键值对塞入
  set_reqList_addKeyValue (state, { key, type }) {
    state.reqList[key] = type
  },
  // 设置reqList，删除已处理键值对
  set_reqList_removeKeyValue (state, key) {
    delete state.reqList[key]
  },
  // 设置各操作的reqId
  set_operationReqId (state, name) {
    state.operationReqId[name] = state.req_id
  }
}

const actions = {
  // 初始化websocket
  initWS ({ state, commit }) {
    if (state.webSocket) {
      state.webSocket.close()
    }
    commit('set_webSocket', initWebsocket())
    sendSock({
      type: '5.1.1',
      body: DH.getPublicKey()
    }, (res) => {
      commit('set_DHSecretKey', new Uint8Array(md5ArrayBuffer(DH.computeSecret(res.body))))
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
